'use strict';
module.exports = {
	/**
	 * 此函数名称
	 * @url client/user/pub/test 前端调用的url参数地址
	 * data 请求参数
	 * @params {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, originalParam
		} = event;
		let {
			customUtil,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			merchandise_info,
			number
		} = data;
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		// 可写与数据库的交互逻辑等等
		// return res
		let car_current = await vk.baseDao.findByWhereJson({
			dbName: "daoju_shopcart",
			whereJson: {
				merchandise_id: merchandise_info.merchandise_id,
				user_id: userInfo._id
			},
			
		})
		
		console.log('car_current', car_current)
		
		let car_number = car_current?.number || 0
		
		if(number + car_number > merchandise_info.inventory){
			// number =  merchandise_info.inventory - car_number
			return {
				msg:"商品加购件大于库存",
				code:-1
			}
		}
		
		
		if (car_current) {
			res.data = await vk.baseDao.update({
				dbName: "daoju_shopcart",
				whereJson: { // 条件
					merchandise_id: merchandise_info.merchandise_id,
					user_id: userInfo._id
				},
				dataJson: { // 需要修改的数据
					...merchandise_info,
					number: _.inc(number),
				}
			});

		} else {
			delete merchandise_info._id
			res.data = await vk.baseDao.add({
				dbName: "daoju_shopcart",
				dataJson: {
					user_id: userInfo._id,
					...merchandise_info,
					number:number
				}
			});
		}
		// let {
		// 	user_id,
		// 	merchandise_list
		// } = data;

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}